import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Alert, Form, Switch, Icon, Input, Select, Button, Row, Col, message, DatePicker } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
import Selector from 'components/selector'
import creditModelService from 'containers/credit-setting/credit-model/credit-model.service'
import moment from 'moment'
import errorMessage from 'share/errorMessage'

class NewCreditModel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: {}
    };
  }

  onCancel = () => {
    this.props.close();
  };

  componentWillReceiveProps(nextProps){
    if(nextProps.params.showSlideFrame && !this.props.params.showSlideFrame){
      let nextData = nextProps.params.nowData;
      let valueWillSet = this.props.form.getFieldsValue();
      Object.keys(valueWillSet).map(key => {
        valueWillSet[key] = nextData[key];
        if(key.indexOf('Date') > -1 && nextData[key])
          valueWillSet[key] = moment(nextData[key]);
      });
      this.props.form.setFieldsValue(valueWillSet)
    }
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { nowData } = this.props.params;
        //这个迭代只做一个类型，暂时写死
        values.modelTypeId = 1001;
        values.tenantId = this.props.company.tenantId;
        this.setState({ loading: true });
        if(nowData.id){
          values = Object.assign({}, JSON.parse(JSON.stringify(nowData)), values);
          values.setOfBooksId = values.setOfBooksId.key;
        }
        values.startDate = values.startDate.utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';
        if(values.endDate){
          values.endDate = values.endDate.utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';
        }
        this.props.form.setFieldsValue({ startDate: moment(values.startDate) });
        creditModelService.saveCreditModel(values).then(res => {
          this.setState({ loading: false });
          message.success(messages('credit-setting.key45')/*保存成功*/);
          this.props.close(true);
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response);
        })
      }
    });
  };

  disabledEndDate = (endValue) => {
    const startValue = this.props.form.getFieldValue('startDate');
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { loading } = this.state;
    const { nowData } = this.props.params;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    return (
      <div>
        <Alert
          message={messages('common.help')/*提示信息*/}
          description={messages('credit-setting.key95')/*同一帐套下同时间段内，只能有一个信用模型生效；同一租户下信用模型代码不允许重复，且保存后不可修改。*/}
          type="info"
          showIcon
        />
        <Form onSubmit={this.handleSave} style={{ marginTop: 30 }}>
          <FormItem {...formItemLayout} label={messages('credit-setting.key86')/*帐套*/}>
            {getFieldDecorator('setOfBooksId', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.select')
                },
              ]
            })(
              <Selector type="setOfBooksByTenant" disabled={!!nowData.id}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key88')/*信用模型代码*/}>
            {getFieldDecorator('modelCode', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
              ]
            })(
              <Input disabled={!!nowData.id}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key87')/*信用模型名称*/}>
            {getFieldDecorator('modelName', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
              ]
            })(
              <Input/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key3')/*信用类型*/}> {messages('credit-setting.key13')/*报销信用*/}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
            {getFieldDecorator('comment', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
              ]
            })(
              <TextArea autosize={{minRows: 2}}
                        style={{minWidth:'100%'}}
                        placeholder={messages('common.please.enter')/*请输入*/}
                        maxLength="500"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key90')/*生效时间*/}>
            {getFieldDecorator('startDate', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.select')
                },
              ]
            })(
              <DatePicker style={{ width: '100%' }} disabledDate={current => {
                return current && current < moment().endOf('day')
              }}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key91')/*失效时间*/}>
            {getFieldDecorator('endDate')(
              <DatePicker style={{ width: '100%' }}
                          disabledDate={this.disabledEndDate}/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')/* 保存 */}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/* 取消 */}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}
const WrappedNewCreditModel = Form.create()(NewCreditModel);

export default connect(mapStateToProps)(WrappedNewCreditModel);
